package com.ruoyi.finance.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @Author: qs
 * @Date: 2025/3/11 19:12
 * @Description:
 **/
@RestController
@RequestMapping("/redistest")
public class RedisController {

    @Autowired
    private RedisTemplate redisTemplate;


    @RequestMapping("/test")
    public void test() {


        String product= "lock:procuct:101";
        //利用redis setnx实现
        Boolean setIfAbsent = redisTemplate.opsForValue().setIfAbsent(product, "苹果手机promax");
        redisTemplate.expire(product, 10, TimeUnit.SECONDS);
        if(!setIfAbsent){
            System.out.println("锁已存在");
        }
        //加锁防止

        try {
            int stock=Integer.parseInt(redisTemplate.opsForValue().get("stock").toString());
            if(stock>0){
                int stocked=stock-1;
                redisTemplate.opsForValue().set("stock",stocked);
                System.out.println("扣减成功,剩余库存:"+stocked);
            }else {
                System.out.println("扣减失败,库存不足");
            }
        }finally {
            redisTemplate.delete(product);
        }



    }
}
